<?php
namespace App\Http\Controllers\Store;

use App\Http\Requests\BasicRequest;
use App\Http\Requests\OrderSendRequest;
use App\Http\Requests\OrderServiceSendRequest;
use App\Http\Requests\StoreRefundRequest;
use App\Http\Requests\RefundInfoRequest;
use App\Http\Requests\RefundConfirmRequest;
use App\Models\House;
use App\Models\Message;
use App\Models\ShopOrder;
use App\Models\ShopOrderLog;
use App\Models\ShopOrderService;
use App\Models\ShopOrderSplit;
use App\Models\ShopRefund;
use App\Models\ShopExpress;
use App\Models\ShopRefundLog;
use App\Http\Requests\OrderDetailRequest;
use Illuminate\Support\Facades\DB;
use App\Models\ShopOrderAddress;
use App\Libraries\KdApi;
use App\Libraries\msg\Push;
use Mockery\Exception;

class OrderController extends CommonController {

    public function order_list(BasicRequest $request){
        $status = $request->input('status',0);
        if($status==7){
            //查看退款列表
            $order_list = $this->refund_list($this->store_id);
        }else{
            $order_list=ShopOrder::where('store_id','=',$this->store_id)->select('order_sn','uid as buyer_id','status','order_amount','created_at','updated_at')
                ->where(['is_store_del'=>0])
                ->when($status,function($query) use ($status){
                    $query->where(['status'=>$status]);
                })->orderBy('id','desc')->pages()->each(function ($v,$k){
                    $v->detail();
                });
        }
        return json_success('OK',$order_list);
    }

	
    private function refund_list($store_id){
        $refund_list=ShopRefund::where(['store_id'=>$store_id,'is_del'=>0])->select('refund_sn','uid as buyer_id','status','refund_amount','order_sn','goods_id','created_at','updated_at')->orderBy('id','desc')->get()->each(function($v,$k){
            $v->detail();
        });
        return $refund_list;
    }

    /*
     *  订单详情
     *  2017/9/23
     */
    public function order_detail(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $order_detail = ShopOrder::where(['order_sn'=>$order_sn,'store_id'=>$this->store_id])->select('order_sn','uid as buyer_id','status','order_type','order_amount','goods_amount','express_amount','created_at')->get()->each(function($v,$k){
            $v->detail();
            $v->store_address();
        })[0];

        if(!$order_detail){
            return json_error('找不到订单');
        }
        if($order_detail->is_del==1){
            return json_error('该订单已删除');
        }
        return json_sussess_obj('OK',$order_detail);
    }

    /*
     *  删除订单
     *  2017/10/5
     */
    public function order_del(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $order_detail = ShopOrder::getOrderDetail($order_sn,'',$this->store_id);
        if(!$order_detail){
            return json_error('找不到订单');
        }

        if($order_detail->status!=7 && $order_detail->status!=8 && $order_detail->status!=5){
            return json_error('当前状态下不能删除订单');
        }
        if($order_detail->is_store_del==1){
            return json_error('该订单已删除');
        }
        $return=DB::transaction(function () use($order_sn) {
            $return = ShopOrder::where(['order_sn'=>$order_sn])->update(['is_store_del'=>1]);
            //插入日志
            ShopOrderLog::createOrderLog($this->uid,$order_sn,'商户删除了订单',$this->store_id);
            return $return;
        });
        return json_success('OK',$return);
    }

    /*
     *  已付款订单取消退款
     *  2017/9/23
     */
    public function order_refund(StoreRefundRequest $request)
    {
        $order_sn = $request->input('order_sn');
        $detail = $request->input('detail');

        if (!$order_sn) {
            return json_error('参数错误');
        }
        $refund_type = 1;
        $order = ShopOrder::getOrderDetail($order_sn, '', $this->store_id);

        $refund_sn = ShopOrder::createOrderSN();

        $check = ShopRefund::where(['order_sn' => $order_sn])->first();
        if ($check) {
            return json_error('该订单已有退款，请勿重复申请');
        }
        if ($this->store->store_type == 1){
            //普通商户
            if ($order->status != 2) {
                return json_error('该订单无法取消');
            }
        }else{
            //服务商待付款和待派单状态直接取消订单
            if($order->status == 2 || $order->status == 1){
                $return=DB::transaction(function () use($order_sn,$order) {
                    $return = ShopOrder::where(['order_sn'=>$order_sn])->update(['status'=>7]);
                    //插入日志
                    ShopOrderLog::createOrderLog($order->uid,$order_sn,'商户取消了订单',$order->uid);
                    //回滚库存
                    ShopOrder::rbackGoodsStock($order_sn);
                    //更新分成表状态
                    ShopOrderSplit::where(['order_sn'=>$order_sn])->update(['status'=>3]);
                    return $return;
                });
                if($return) {
                    Message::message_push($order->uid,'store_order_cancel','您有一个订单已被商家取消，订单号：'.$order_sn.'，取消原因:'.$detail.'，请您谅解。',$order_sn);
                    return json_success('取消成功!', ['refund_sn' => $refund_sn]);
                }else{
                    return json_error('取消失败');
                }
            }
        }
        $refund_info = array(
            'order_sn'=>$order_sn,
            'refund_sn'=>$refund_sn,
            'goods_id'=>'',
            'reason'=>'商户主动取消订单',
            'detail'=>$detail,
            'refund_reply'=>'商户主动取消订单',
            'goods_amount'=>0,
            'status'=>1,
            'store_id'=>$order->store_id,
            'order_amount'=>$order->order_amount,
            'refund_amount'=>$order->order_amount,
            'reason_id'=>0,
            'uid'=>$order->uid,
            'refund_type'=>$refund_type,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
        );
        $return = DB::transaction(function () use($refund_info) {
            $create = ShopRefund::insert($refund_info);
            if (!$create) {
                throw new \Exception('插入退款表失败');
            }
            $update = ShopOrder::where(['order_sn' => $refund_info['order_sn']])->update(['status' => 7]);
            if (!$update) {
                throw new \Exception('更改订单状态失败');
            }
            //插入申请退款记录
            $details = '商户发起退款';
            $create = ShopOrderLog::createOrderLog($refund_info['uid'], $refund_info['order_sn'], $details, $refund_info['uid'], 2);
            if (!$create) {
                throw new \Exception('插入订单日志失败');
            }
            $create = ShopRefundLog::createOrderLog($refund_info['uid'], $refund_info['refund_sn'], $details, $refund_info['uid'], 1);
            if (!$create) {
                throw new \Exception('插入退款日志失败');
            }
            Message::message_push($refund_info['uid'],'store_order_cancel','您有一个订单已被商家取消，订单号：'.$refund_info['order_sn'].'，订单金额将原路退回，退款原因:'.$refund_info['detail'].'，请您谅解。',$refund_info['order_sn']);

            //调用退款接口
            return ShopRefund::AppRefund($refund_info);
        });
        return json_success('取消成功!',['refund_sn'=>$refund_sn]);
    }
    //发货
    public function send(OrderSendRequest $request){

        $return = DB::transaction(function () use($request) {
            $address=array();
            $order_sn=$request->input('order_sn');
            $address['express_id']=$request->input('express_id');
            $address['express_code']=$request->input('express_code');
            $address['express_name']=$request->input('express_name');
            $address['express_mobile']=$request->input('express_mobile');

            if($address['express_id']==0){
                $address['express_name'] = '商家配送：'.$address['express_name'];
                $address['express_type'] = 2;

                $isMob="/^1[3-5,8]{1}[0-9]{9}$/";
                if(!preg_match($isMob,$address['express_mobile']))
                {
                    return json_error('请输入手机号');
                }
            }else{
                $express_info = ShopExpress::where(['id'=>$address['express_id']])->select('express_name','express_mobile','express_code')->first();
                $address['express_name'] = $express_info->express_name;
                $address['express_mobile'] = $express_info->express_mobile;
                $address['express_company_code'] = $express_info-> express_code;
            }
            $check=ShopOrder::where(['order_sn'=>$order_sn,'status'=>2])->first();
            if(!$check){
                throw new \Exception('该订单无法发货');
            }
            ShopOrderAddress::where(['order_sn'=>$order_sn])->update($address);

            ShopOrder::where(['order_sn'=>$order_sn,'status'=>2])->update(['status'=>3]);

            //发送用户消息
            Message::message_push($check->uid,'order_send','您的订单已经发货，订单号：'.$order_sn.'。',$order_sn);

            ShopOrderLog::createOrderLog($this->uid,$order_sn,'该订单已发货',$this->store->store_name);
            return true;
        });
        if($return){
            return json_success('OK');
        }else{
            return json_error('系统错误，请重试');
        }

    }

    //派单
    public function service_send(OrderServiceSendRequest $request){
        $isMob="/^1[3-5,8]{1}[0-9]{9}$/";
        if(!preg_match($isMob,$request->input('service_mobile')))
        {
            return json_error('请输入手机号');
        }
        $return = DB::transaction(function () use($request) {
            $service=array();
            $order_sn=$request->input('order_sn');
            $service['service_name']=$request->input('service_name');
            $service['service_mobile']=$request->input('service_mobile');
            $service['order_sn']=$order_sn;

            $check=ShopOrder::where(['order_sn'=>$order_sn,'status'=>2])->first();
            if(!$check){
                throw new \Exception('该订单无法派单');
            }
            $remark = $request->input('remark','谢谢');
            $address = ShopOrderAddress::where(['order_sn'=>$order_sn])->first();

            $param[0] = $address->name;
            $param[1] = House::where(['house_id'=>$address->house_id])->value('house_detail');
            $param[2] = $address->mobile;
            $param[3] = $remark? $remark:'谢谢';
            ShopOrderService::create($service);
            ShopOrder::where(['order_sn'=>$order_sn,'status'=>2])->update(['status'=>1]);

            //发送用户消息
            Message::message_push($check->uid,'order_service_send','商家已派单,服务人员联系电话：'.$service['service_mobile'].'。',$order_sn);
            send_message($service['service_mobile'],'派单通知',$param);
            ShopOrderLog::createOrderLog($this->uid,$order_sn,'该订单已派单',$this->store->store_name);

            return true;
        });
        if($return){
            return json_success('OK');
        }else{
            return json_error('系统错误，请重试');
        }
    }

    //获取物流公司列表
    public function express_company(){
        $return=ShopExpress::where(['status'=>1])->select('express_name','id')->get();
        return json_success('OK',$return);
    }

    /*
     *  订单物流信息
     *  2017/10/5
     */
    public function express(OrderDetailRequest $request){
        $order_sn =$request->input('order_sn');
        $order_detail = ShopOrder::getOrderDetail($order_sn,'',$this->store_id);
        if(!$order_detail){
            return json_error('找不到订单');
        }
        if($order_detail->is_del==1){
            return json_error('该订单已删除');
        }
        if($order_detail->status<=2){
            return json_error('订单暂未发货');
        }

        $return = array();
        $return['status'] = $order_detail->status;
        $return['order_sn'] = $order_sn;

        $express = ShopOrderAddress::where(['order_sn'=>$order_sn])->first();
        $return['expresss_name'] = $express->express_name;
        $return['company_id'] = $express->express_id;
        $return['express_code'] = $express->express_code;
        $return['express_mobile'] = $express->express_mobile;
        if($express->express_id !=0) {
            $kd_api = new KdApi();
            $express_info = $kd_api->getOrderTracesByJson($order_sn, $express->express_company_code, $express->express_code);
            $return['express_info'] = json_decode($express_info, true);
        }else{
            $return['express_info'] = new \stdClass();
        }
        return json_sussess_obj('OK',$return);
    }

    /*
     * 订单退款详情
     */
    public function refund_info(RefundInfoRequest $request){
        $refund_sn = $request->input('refund_sn');
        $order_sn = $request->input('order_sn');
        $goods_id = $request->input('goods_id');
        if($refund_sn){
            $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn,'store_id'=>$this->store_id,'is_del'=>0])->select('refund_sn','refund_reply','order_sn','status','refund_amount','reason','detail','refund_type','created_at')->get();
        }else if($order_sn && $goods_id){
            $refund_info = ShopRefund::where(['goods_id'=>$goods_id,'store_id'=>$this->store_id,'order_sn'=>$order_sn,'is_del'=>0])->select('refund_sn','refund_reply','order_sn','status','refund_amount','reason','detail','refund_type','created_at')->get();
        }else{
            return json_error('参数错误');
        }

        if(!$refund_info->first()){
            return json_error('未找到退款申请');
        }else{

            $refund_info=$refund_info->each(function($v,$k){
                $v->detail();
                $v->other_detail();
            })['0'];
            return json_success('OK',$refund_info);
        }
    }

    /*
    * 订单退款处理
    */
    public function refund_confirm(RefundConfirmRequest $request){
        $refund_sn = $request->input('refund_sn');
        $status = $request->input('status');
        $refund_reply = $request->input('detail');

        $return=DB::transaction(function () use($refund_sn,$refund_reply,$status) {
            $refund_status = ShopRefund::where(['refund_sn'=>$refund_sn])->where('status','=',1)->value('status');
            if(!$refund_status){
                throw new Exception('退款单状态有误或已处理，请重试');
            }
            $update = ShopRefund::where(['refund_sn'=>$refund_sn])->update(['refund_reply'=>$refund_reply]);
            if(!$update){
                throw new Exception('更新订单状态失败');
            }
            $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn])->first()->toArray();
            if($status == 2) {
                //同意退款
                $return = ShopRefund::AppRefund($refund_info, '商家');
                if($return){
                    ShopOrderSplit::refund_success($refund_info['order_sn'],$refund_info['refund_amount']);
                    Message::message_push($refund_info->uid,'store_refund_success',$this->store->store_name.'已同意退款'.$refund_info['amount'].'元。',$refund_sn);
                }
            }else if ($status ==3){
                //拒绝退款
                $refund_info = ShopRefund::where(['refund_sn'=>$refund_sn])->first();
                ShopRefund::where(['refund_sn'=>$refund_sn])->where(['refund_sn'=>$refund_sn])->update(['status'=>3]);
                ShopRefundLog::createOrderLog($refund_info->uid,$refund_sn,'商家拒绝退款','商家',$status);
                ShopOrderLog::createOrderLog($refund_info->uid,$refund_info->order_sn,'商家拒绝退款','商家',1);
                //发送用户消息
                Message::message_push($refund_info->uid,'store_refund_fail',$this->store->store_name.'已拒绝退款,回复详情'.$refund_reply.'。',$refund_sn);
                return true;
            }else{
                throw new Exception('参数错误');
            }
        });
        return json_success('处理完成',$return);

    }
}